﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using Infrastructure;
using SubsDownloader.Core.AppSettings;
using SubsDownloader.Core.Interfaces;

namespace SubsDownloader
{
    public partial class OptionsDlg : Form
    {
        List<string> _workingFolders = new List<string>();

        public OptionsDlg ()
        {
            InitializeComponent();

        }

        private void ButtonAddClick ( object sender, EventArgs e )
        {
            if (!string.IsNullOrEmpty( _textBoxPath.Text ) && Directory.Exists( _textBoxPath.Text ))
            {
                AddDirectory( _textBoxPath.Text );
                _textBoxPath.Text = string.Empty;
            }
            else if (_folderBrowserDialog.ShowDialog( this ) == DialogResult.OK)
            {
                AddDirectory( _folderBrowserDialog.SelectedPath );
            }
        }

        private void AddDirectory ( string directory )
        {
            foreach (var monitoredFolder in _workingFolders)
            {
                if (directory == monitoredFolder)
                {
                    MessageBox.Show( string.Format( "Cannot add direcotry: {0}. \n\rDhe directory already exists", directory ) );
                    return;
                }
                else if (monitoredFolder.StartsWith( directory ))
                {
                    MessageBox.Show( string.Format( "Cannot add direcotry: {0}. \n\rDirectory is parent for: {1}", directory, monitoredFolder ) );
                    return;
                }
                else if (directory.StartsWith( monitoredFolder ))
                {
                    MessageBox.Show( string.Format( "Cannot add direcotry: {0}. \n\rDirectory is nested to {1}", directory, monitoredFolder ) );
                    return;
                }
            }
            _workingFolders.Add( directory );
            _listBoxFolders.Items.Add( directory );
        }

        private void ButtonRemoveClick ( object sender, EventArgs e )
        {
            if (_listBoxFolders.SelectedItem != null)
            {
                _workingFolders.Remove( _listBoxFolders.SelectedItem.ToString() );
                _listBoxFolders.Items.Remove( _listBoxFolders.SelectedItem );
                _textBoxPath.Clear();
            }
        }

        private void ListBoxAddSelectedIndexChanged ( object sender, EventArgs e )
        {
            if (_listBoxFolders.SelectedItem != null)
            {
                _buttonRemove.Enabled = true;
                _textBoxPath.Text = _listBoxFolders.SelectedItem.ToString();
            }
            else
            {
                _buttonRemove.Enabled = false;
            }
        }

        private void OptionsDlg_Load ( object sender, EventArgs e )
        {
            LoadSettings();
        }

        private void LoadSettings()
        {
            tabControl1.TabPages.Remove( _tabPageProviders );
            var subtitlesSettings = SettingsManager.Instane.GetSettings<SubtitlesSettings>();
            _numericUpDownThreadCount.Value = subtitlesSettings.WorkerThreads;
           
            _trackBarRisk.Value = subtitlesSettings.DownloadRisk;
            label7.Text = subtitlesSettings.DownloadRisk.ToString();

            _checkBoxPreferFolderName.Checked = subtitlesSettings.PrefreFolderName;
            var folderScanerSettings = SettingsManager.Instane.GetSettings<FolderScanerSettings>();
            _checkBoxOnlyWithoutSubs.Checked = folderScanerSettings.LoadOnlyFilesWithoutSubtitles;
            _numericUpDownWait.Value = (decimal)TimeSpan.FromMilliseconds( subtitlesSettings.WaitForUserToSelect ).TotalMinutes;
            _numericUpDownMonitor.Value = (decimal)TimeSpan.FromMilliseconds( folderScanerSettings.MonitorInterval ).TotalMinutes;

            _workingFolders = folderScanerSettings.FolderToMonitor.ToList();
            _listBoxFolders.Items.AddRange( _workingFolders.ToArray() );

            string subtitleTypes = subtitlesSettings.SubtitlesTypes.Aggregate( string.Empty, ( current, subtitlesType ) => current + ( subtitlesType + ',' ) );
            _textBoxSubtitleTypes.Text = subtitleTypes;

            string fileTypes = folderScanerSettings.MediaTypes.Aggregate( string.Empty, ( current, subtitlesType ) => current + ( subtitlesType + ',' ) );
            _textBoxFileTypes.Text = fileTypes;


            objectListView1.SetObjects( subtitlesSettings.Expressions );
        }

        private void LoadSubsProviders ()
        {
            var iSubsDownloaders = TypeLoader.Instance.GetTypes( typeof( ISubsDownloader ) );
            foreach (var iSubsDownloader in iSubsDownloaders)
            {
                ISubsDownloader instance = (ISubsDownloader)Activator.CreateInstance( iSubsDownloader );
                _flowLayoutPanel.Controls.Add( new CheckBox() { Text = instance.Name } );
            }
        }

        private void ButtonOkClick ( object sender, EventArgs e )
        {
            var subtitlesSettings = SettingsManager.Instane.GetSettings<SubtitlesSettings>();
            var folderScanerSettings = SettingsManager.Instane.GetSettings<FolderScanerSettings>();

            subtitlesSettings.WorkerThreads = (int)_numericUpDownThreadCount.Value;
            subtitlesSettings.WaitForUserToSelect = (int)TimeSpan.FromMinutes( (double)_numericUpDownWait.Value ).TotalMilliseconds;

            var subTypes = _textBoxSubtitleTypes.Text.Split( new[] { ',' }, StringSplitOptions.RemoveEmptyEntries );
            subtitlesSettings.SubtitlesTypes = subTypes.ToList();

            var fileTypes = _textBoxFileTypes.Text.Split( new[] { ',' }, StringSplitOptions.RemoveEmptyEntries );
            folderScanerSettings.MediaTypes = fileTypes.ToList();
           

            subtitlesSettings.DownloadRisk = _trackBarRisk.Value;
            subtitlesSettings.PrefreFolderName = _checkBoxPreferFolderName.Checked;

            folderScanerSettings.MonitorInterval = (int)TimeSpan.FromMinutes( (double)_numericUpDownMonitor.Value ).TotalMilliseconds;
            folderScanerSettings.FolderToMonitor = _workingFolders;
            folderScanerSettings.LoadOnlyFilesWithoutSubtitles = _checkBoxOnlyWithoutSubs.Checked;

            SettingsManager.Instane.SaveSettings();
        }

        private void TrackBarRiskValueChanged ( object sender, EventArgs e )
        {
            ShowDuynamicToolTip();
        }

        private void TrackBarRiskMouseHover ( object sender, EventArgs e )
        {
            ShowDuynamicToolTip();
        }

        private void ShowDuynamicToolTip ()
        {
            _toolTipRick.ToolTipTitle = string.Format( "Risk Level: {0}", _trackBarRisk.Value );
            switch (_trackBarRisk.Value)
            {
                case 0:
                    _toolTipRick.SetToolTip( _trackBarRisk, string.Format( "User always need to select the subtitles" ) );
                    break;
                case 1:
                    _toolTipRick.SetToolTip( _trackBarRisk, string.Format( "Chooses the titles only of there is a perfecr match" ) );
                    break;
                case 2:
                    _toolTipRick.SetToolTip( _trackBarRisk, string.Format( "Chooses the titles by a guessing the best match" ) );
                    break;
                case 3:
                    _toolTipRick.SetToolTip( _trackBarRisk, string.Format( "Download the first match" ) );
                    break;
            }
        }

        private void TrackBarRiskScroll ( object sender, EventArgs e )
        {
            label7.Text = _trackBarRisk.Value.ToString();
        }
   
        private void ButtonResetClick ( object sender, EventArgs e )
        {
            var dialogResult= MessageBox.Show( "All settings will be set to defaults.\n Are you sure?","Reset Settings",MessageBoxButtons.YesNo );
            if(dialogResult == DialogResult.Yes)
            {
                SettingsManager.Instane.ResetSettings();
                LoadSettings();
            }
        }
    }
}
